package com.wwg.threads.threads_interactive.reentrant_lock_conditon;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @类描述:
 * @Author wwg
 * @date: 2021/7/28 18:28
 * @Version: 1.0
 **/
public class ReentrantLockWithConditionTest {

    private static final Logger log = LoggerFactory.getLogger(ReentrantLockWithConditionTest.class);


    public static void main(String[] args) throws InterruptedException {
        List<String> list = new ArrayList<>();
        ReentrantLock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        Thread t1 = new Thread(() -> {
            lock.lock();
            log.debug("size = {}", list.size());
            if (list.size() != 5) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            log.debug("开始执行任务!");
            lock.unlock();
        });

        Thread t2 = new Thread(() -> {
            lock.lock();
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(100);
                    list.add("abc");
                    log.debug("第{}次循环", i + 1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (list.size() == 5) {
                    condition.signal();// 并不是立即释放锁，也是等到当前任务执行完成
                }
            }
            lock.unlock();
        });

        t1.start();
        Thread.sleep(1000);
        t2.start();

    }
}
